<template>
    <div class="app-container">
        <div class="customContainer" v-show="tab_view==1">
            <!-- 搜索头 -->
            <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
                <el-form-item>
                    <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                                    :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-select
                            placeholder="选择筛选条件"
                            v-model="formInline.type"
                            style="width:150px"
                            filterable
                    >
                        <el-option
                                v-for="item in SearchList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-show="formInline.type=='0'" style="width: 200px" v-model="formInline.sample_name" placeholder="请输入短信名称" @keyup.enter.native="fetchData"></el-input>
                    <el-input v-show="formInline.type=='1'" style="width: 200px" v-model="formInline.template_name" placeholder="请输入模板名称" @keyup.enter.native="fetchData"></el-input>
                    <el-input v-show="formInline.type=='2'" style="width: 200px" v-model="formInline.template_code" placeholder="请输入模板CODE" @keyup.enter.native="fetchData"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">搜索</el-button>
                </el-form-item>
                <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">发短信</el-button>
            </el-form>

            <!--       表格内容-->
            <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading"
                      :default-sort = "{prop: 'create_time', order: 'descending'}">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                </el-table-column>
                <el-table-column align="center" label="短信名称" prop="name"></el-table-column>
                <el-table-column align="center" label="短信内容" width="300px">
                    <template slot-scope="scope">
                        <div class="longlinks">{{scope.row.content}}</div>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="模板名称" prop="template_name"></el-table-column>
                <el-table-column align="center" label="模板CODE" prop="code"></el-table-column>
                <el-table-column align="center" label="发送时间" prop="send_time" sortable></el-table-column>
                <el-table-column align="center" label="发送状态">
                    <template slot-scope="scope">
                        {{scope.row.status==1?"未发送":"已发送"}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="发送总数" prop="num"></el-table-column>
<!--                <el-table-column align="center" label="成功数" prop="win_num"></el-table-column>-->
<!--                <el-table-column align="center" label="失败数">-->
<!--                    <template slot-scope="scope">-->
<!--                        <div @click="PhoneError(scope.row)" style="color: #36a3f7">{{scope.row.lose_num}}</div>-->
<!--                    </template>-->
<!--                </el-table-column>-->
                <el-table-column align="center" label='操作'>
                    <template slot-scope="scope">
                        <el-button  type="primary" plain size="mini" @click="detailsList(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 短信详情-->
        <div v-show="tab_view==2" class="customContainer">
            <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
            <div class="tab_title">{{top_title}}</div>
            <div v-show="isNew">
                <dj-tab :data="step_list" :isNew="isNew" :tab_step="tab_step" @goStep="goStep"></dj-tab>
            </div>
            <div v-show="tab_step==1" class="info">
                <el-form
                        ref="infoFormList"
                        :model="infoFormList"
                        :disabled="isDisabled"
                >
                    <div class="op_title">短信名称</div>
                    <el-form-item label="" label-width="50px">
                        <el-input
                                v-model="infoFormList.name"
                                style="width:80%"
                                disabled
                        ></el-input>
                    </el-form-item>
                    <div class="op_title">短信内容</div>
                    <el-form-item label="" label-width="50px">
                        <el-input
                                type="textarea"
                                :rows="3"
                                v-model="infoFormList.content"
                                style="width:80%"
                                disabled
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div v-show="tab_step==2" class="info">
                <div class="op_title">选择发送对象</div>
                <el-form
                        ref="infoFormList"
                        :model="infoFormList"
                        :disabled="isDisabled"
                >
                    <el-form-item label="" label-width="50px">
                        <el-select
                                placeholder="请选择发送对象"
                                v-model="infoFormList.type"
                                style="width:250px"
                                filterable
                        >
                            <el-option
                                    v-for="item in infoForm_list"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <div class="op_title" v-show="infoFormList.type==1">单个用户</div>
                    <el-form-item v-show="infoFormList.type==1" label="手机号" label-width="80px">
                        <el-input style="width: 280px" v-model="infoFormList.phone" placeholder="请输入11位的手机号" :maxlength="11" show-word-limit></el-input>
                    </el-form-item>

                    <div class="op_title" v-show="infoFormList.type==2">导入用户 <span style="color: #ccc;font-size: 12px;margin-left: 15px">根据上传文件批量导入用户手机号，文件格式支持：xls、xlxs，可导入手机号数量1~50000</span></div>
                    <el-form-item label="" label-width="50px" v-show="infoFormList.type==2">
                        <!-- 导入用户 -->
                        <div class="upload" v-show="!isDisabled">
                            <el-upload
                                    style="margin-bottom:20px"
                                    ref="upload"
                                    action="/"
                                    accept=".xls, .xlsx"
                                    :on-change="uploadChange"
                                    :show-file-list="true"
                                    :auto-upload="false"
                                    :limit="1"
                                    :disabled="beforeUploadLoading"
                            >
                                <el-button
                                        @click="beforeUpload"
                                        type="primary"
                                        size="small"
                                        :loading="beforeUploadLoading"
                                >{{user_phone.length||phone_num>=0?"重新导入":"导入用户"}}</el-button>
                            </el-upload>
                            <div class="download">
                                <el-button @click="uploadTemplate" type="primary" size="small">下载模板</el-button>
                            </div>
                        </div>
                        <div v-if="bad_phone_num>0||phone_num>=0" class="upload_info">
                            <div v-show="isNew!=2" class="upload_info_title">仅对有效手机号发放</div>
                            <div class="upload_info_num">有效手机号：{{phone_num}}个</div>
                            <div v-show="bad_phone_num>0" class="upload_info_bad_num">
                                无效手机号：{{bad_phone_num}}个
                                <el-button
                                        @click="uploadPhone"
                                        :loading="uploadBadLoading"
                                        type="primary"
                                        size="small"
                                >下载</el-button>
                            </div>
                            <div  v-show="isNew!=2 || !isDisabled"
                                  class="upload_remark"
                            >文件上传后对手机号进行筛选，筛选出重复的手机号、格式不对的手机号、不是纯数字的手机号、手机号位数不够的手机号、系统里不存在的手机号，视为无效手机号</div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div v-show="tab_step==3" class="info">
                <el-form
                        ref="infoFormList"
                        :model="infoFormList"
                        :disabled="isDisabled"
                >
                    <div class="op_title" v-show="!isDisabled">选择发送时间 <span style="color: #ccc;font-size: 12px;margin-left: 15px">0:00:00—06:00:00不能发送</span></div>
                    <el-form-item label="" label-width="50px"   v-show="!isDisabled">
                        <el-radio-group v-model="infoFormList.sendType">
                            <div style="margin-bottom: 40px">
                                <el-radio label="1">立即发送</el-radio>
                            </div>
                            <div>
                                <el-radio label="2">定时发送</el-radio>
                                <el-date-picker
                                        v-show="infoFormList.sendType==2"
                                        v-model="infoFormList.sendTime"
                                        value-format="yyyy-MM-dd HH"
                                        type="datetime" align="right"
                                        :picker-options="pickerOptions1"
                                        placeholder="选择日期时间"
                                ></el-date-picker>
                            </div>
                        </el-radio-group>
                    </el-form-item>
                    <div class="op_title" v-show="isDisabled">短信发送时间</div>
                    <el-form-item label="发送时间：" v-show="isDisabled" label-width="120px">
                        <div>{{infoFormList.sendTime}}</div>
                    </el-form-item>
                </el-form>
            </div>
            <div style="text-align:right;margin-bottom:20px">
                <el-button v-show="tab_step>1&&isNew==1" @click="tab_step--" plain size="small">上一步</el-button>
                <el-button v-show="tab_step<3&&isNew==1" @click="goNext" type="primary" size="small">下一步</el-button>
                <el-button v-show="tab_step==3&&isNew==1" @click="saveSms" type="primary" size="small">保存</el-button>
            </div>
        </div>

        <el-dialog  title="发送失败手机号" :visible.sync="errorPhoneDialog" width="600px" height="500px">
            <el-table highlight-current-row :data="errorPhoneList" border size="mini" v-loading.body="formPhoneDialong.listLoading">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                </el-table-column>
                <el-table-column align="center" label="手机号" prop="phone"></el-table-column>
            </el-table>
            <div class="bottom_box" style="margin-top: 20px">
                <el-pagination class="pull-left" background @current-change="dialongPhoneChange" :current-page.sync="formPhoneDialong.currentPage" :page-size="20"
                               layout="prev, pager, next, jumper" :total="formPhoneDialong.totalDataNumber">
                </el-pagination>
            </div>
        </el-dialog>
<!--        -->
        <!-- 弹框 -->
        <el-dialog  title="选择短信" :visible.sync="addTypeDialog" width="1200px" height="500px">
            <div class="main">
                <el-form :inline="true" class="demo-form-inline" size="small">
                    <el-form-item>
                        <el-date-picker style="width:240px" v-model="formDialongPickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                                        :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-select
                                placeholder="选择筛选条件"
                                v-model="formDialong.type"
                                style="width:150px"
                                filterable
                        >
                            <el-option
                                    v-for="item in SearchList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-show="formDialong.type=='0'" style="width: 200px" v-model="formDialong.sample_name" placeholder="请输入短信名称" @keyup.enter.native="fetchData"></el-input>
                        <el-input v-show="formDialong.type=='1'" style="width: 200px" v-model="formDialong.template_name" placeholder="请输入模板名称" @keyup.enter.native="fetchData"></el-input>
                        <el-input v-show="formDialong.type=='2'" style="width: 200px" v-model="formDialong.template_code" placeholder="请输入模板CODE" @keyup.enter.native="fetchData"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="dialongFetchData">搜索</el-button>
                    </el-form-item>
                </el-form>
                <!--       表格内容-->
                <el-table highlight-current-row :data="formDialongList" border size="mini" v-loading.body="formDialongInline.listLoading" max-height="500px"
                          :default-sort = "{prop: 'create_time', order: 'descending'}">
                    <el-table-column align="center" label='序号' width="50">
                        <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                    </el-table-column>
                    <el-table-column align="center" label="短信名称" prop="name"></el-table-column>
                    <el-table-column align="center" label="短信内容" width="300px">
                        <template slot-scope="scope">
                            <div class="longlinks">{{scope.row.content}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="模板名称" prop="name"></el-table-column>
                    <el-table-column align="center" label="模板CODE" prop="code" width="100px"></el-table-column>
                    <el-table-column align="center" label="创建时间" prop="create_time" sortable></el-table-column>
                    <el-table-column align="center" label='操作'>
                        <template slot-scope="scope">
                            <el-button  type="primary" plain size="mini" @click="contentDetails(scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="bottom_box">
                    <el-pagination class="pull-left" background @current-change="dialongCurrentChange" :current-page.sync="formDialongInline.currentPage" :page-size="20"
                                   layout="prev, pager, next, jumper" :total="formDialongInline.totalDataNumber">
                    </el-pagination>
                </div>
            </div>
        </el-dialog>

        <!-- 自定义底部 -->
        <div class="bottom_box" v-show="tab_view==1">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                           layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import {
        notificationList,
        notificationPage,
        getMessageInfo,
        getMessageInfoPage,
        importPhone,
        sendMessage,
        notificationInfo
    } from "@/api/information/short_record";
    import {
        pickerOptionsY,
        pickerDateOneMonth,
        pickerOptionsGtDay,
        pickerOptionsGtDayHours,
        optionMaxTime369
    } from "@/utils";
    import {
        mobile
    } from "@/utils/validate";
    import { djTab } from "@/components/tab";
    import XLSX from "xlsx";
    let phoneNum,phone;
    export default {
        name: "short_record",
        components: {
            "dj-tab": djTab,
        },
        data(){
            return{
                list: [],  //数据
                tab_view:"1",
                isDisabled:false,
                listLoading: false,  //表格换场动画
                errorPhoneDialog:false,
                errorPhoneList:[],
                errorPhoneListDialog:[],
                pickerOptions: pickerOptionsY(),
                pickerOptions1: pickerOptionsGtDayHours(),
                pickerDate: pickerDateOneMonth(),
                formInline: {   //主页的搜索数据
                    begin_time: "",//开始时间，结束时间
                    end_time: "",
                    type:"0",
                    sample_name:"",
                    template_name:"",
                    template_code:""
                },
                SearchList:[{id:"0",name:"短信名称"},{id:"1",name:"模板名称"},{id:"2",name:"模板CODE"}],
                addTypeDialog:false,
                currentPage: 1,  //主页的分页
                totalDataNumber: 0, //主页的总条目数
                formDialongList:[], //弹框里面的表格数据
                formDialongPickerDate:pickerDateOneMonth(),
                formDialong:{
                    begin_time: "",//开始时间，结束时间
                    end_time: "",
                    type:"0",
                    sample_name:"",
                    template_name:"",
                    template_code:""
                },
                formDialongInline:{
                    currentPage: 1,
                    totalDataNumber: 0,
                    listLoading:false,
                },
                formPhoneDialong:{
                    currentPage: 1,
                    totalDataNumber: 0,
                    listLoading:false,
                },
                top_title: "短信预览", //详情页的标题
                step_list: ["1.短信预览", "2.发送对象", "3.发送设置"],
                isNew: 1, //1 新增  2 详情
                tab_step: 1,
                infoFormList:{
                    template_id:"",
                    sample_id:"",
                    name:"",
                    content:"",
                    type:"",
                    phone:"",
                    key:"",
                    sendType:"",
                    sendTime:""
                },
                beforeUploadLoading: false,
                uploadBadLoading: false,
                user_phone: [], //导入手机号
                user_bad_phone: [], //不符合手机号
                phone_num_list:[],//有效手机号
                phone_num: -1, //有效手机号数量
                bad_phone_num: 0, //无效手机号数量
                infoForm_list:[{id:"2",name:"导入用户"},{id:"1",name:"单独发送"}]
            }
        },
        activated() {
            let index = this.$route.params.index;
            if(index == 2){
                this.clearDate();
                let data = this.$route.params.data;
                this.infoFormList.name = data.name;
                this.infoFormList.content = data.content;
                this.infoFormList.sample_id = data.id;
                this.infoFormList.template_id = data.template_id;
                this.tab_view = 2;
                this.isNew = 1;
                this.tab_step = 1;
            }
        },
        watch:{
            "formInline.type"(oldValue,newValue){
                switch (this.formInline.type) {
                    case '0':
                        this.formInline.template_code="";
                        this.formInline.template_name="";
                        break;
                    case '1':
                        this.formInline.sample_name="";
                        this.formInline.template_code="";
                        break;
                    case '2':
                        this.formInline.sample_name="";
                        this.formInline.template_name="";
                        break;
                }
            },
            "formDialong.type"(oldValue,newValue){
                switch (this.formDialong.type) {
                    case '0':
                        this.formDialong.template_code="";
                        this.formDialong.template_name="";
                        break;
                    case '1':
                        this.formDialong.sample_name="";
                        this.formDialong.template_code="";
                        break;
                    case '2':
                        this.formDialong.sample_name="";
                        this.formDialong.template_name="";
                        break;
                }
            },
            "infoFormList.type"(oldValue,newValue){
                if(this.infoFormList.type == 2){
                    this.beforeUpload();
                }else{
                    this.infoFormList.phone = "";
                }
            }
        },
        created() {
            this.listArray();
        },
        methods:{
            fetchData(){ //搜索
                optionMaxTime369(this.pickerDate).then(()=>{
                    this.formInline.begin_time=this.pickerDate[0];
                    this.formInline.end_time=this.pickerDate[1];
                    this.listArray();
                });
            },
            listArray(){  //获取数据
                this.listLoading = true;
                this.formInline.begin_time=this.pickerDate[0];
                this.formInline.end_time=this.pickerDate[1];
                this.list = [];
                notificationPage(this.formInline).then(response=>{
                    this.totalDataNumber = response.data.count / 1;
                    if (this.totalDataNumber == 0) {
                        this.listLoading = false;
                    } else {
                        notificationList(this.formInline).then(res=>{
                            this.list = res.data;
                            this.listLoading = false;
                        });
                    }
                });
            },
            handleCurrentChange(val) {  //获取某个分页的数据
                this.listLoading = true;
                notificationList(this.formInline,val).then(res=>{
                    this.list = res.data;
                    this.listLoading = false;
                }).catch(res => {
                    this.listLoading = false;
                });
            },
            addTypeClick() {  //发送短信
                this.addTypeDialog = true;
                //获取模板数据
                this.dialongFetchData();
            },
            PhoneError(row){ //弹框失败手机号
                if(row.lose_num != 0){
                    this.errorPhoneDialog = true;
                    this.errorPhoneList = [];
                    this.errorPhoneListDialog = [];
                    notificationInfo({id:row.id}).then((res)=>{
                        if(res.code == 1){
                            this.formPhoneDialong.totalDataNumber = res.data.phone_list.length / 1;
                            this.errorPhoneListDialog = res.data.phone_list;
                            this.errorPhoneList = this.errorPhoneListDialog.slice(0,20);
                        }
                    })
                }else{
                    this.formPhoneDialong.totalDataNumber = 1;
                    this.errorPhoneDialog = true;
                    this.errorPhoneList = [];
                }
            },
            dialongPhoneChange(val) {  //弹框失败手机号  获取某个分页的数据
                this.errorPhoneList = this.errorPhoneListDialog.slice((val-1)*20,val*20);
            },
            detailsList(listArray){
                [phoneNum,phone] = ["",""];
                notificationInfo({id:listArray.id}).then((res)=>{
                    if(res.code == 1){
                        this.infoFormList.sample_id = res.data.id;
                        this.infoFormList.template_id = res.data.template_id;
                        this.infoFormList.name = res.data.name;
                        this.infoFormList.content = res.data.content;
                        this.infoFormList.type = res.data.type;
                        this.infoFormList.sendTime = res.data.send_time;
                        phoneNum = res.data.num; //不知道为何赋值不上，所以直接全局变量
                        phone = res.data.phone_list[0].phone;
                    }
                }).then(()=>{
                    this.phone_num = phoneNum;
                    this.infoFormList.phone = phone;
                    this.tab_view=2;
                    this.isNew =  2;
                    this.tab_step = 1;
                    this.isDisabled = true;
                    this.top_title="短信详情";
                })
            },
            contentDetails(listArray){  //发送短信页面
                this.tab_view=2;
                this.isNew =  1;
                this.tab_step = 1;
                this.isDisabled=false;
                this.top_title="短信预览";
                this.addTypeDialog = false;
                this.$refs.infoFormList.resetFields();

                this.infoFormList.sample_id = listArray.id;
                this.infoFormList.template_id = listArray.template_id;
                this.infoFormList.name = listArray.name;
                this.infoFormList.content = listArray.content;
            },
            saveSms(){  // 保存 发送短信
                if(this.infoFormList.sendType){
                    if(this.infoFormList.sendType == 2){
                        if(this.infoFormList.sendTime){
                            let status = this.saveTime();
                            if(!status){
                                return;
                            }
                        }else{
                            this.$message.error("请设置定时发送时间");
                            return
                        }
                    }
                }else{
                    this.$message.error("请选择发送时间");
                    return
                }
                // console.log(this.infoFormList)
                let phone_list=[];
                let send_time = "";
                if(this.infoFormList.type == 1){
                    phone_list.push(this.infoFormList.phone);
                }else{
                    phone_list = this.phone_num_list;
                }

                if(this.infoFormList.sendType==1){
                    send_time = "";
                }else {
                    send_time = this.infoFormList.sendTime + ":00:00";
                }

                let data={
                    template_id:this.infoFormList.template_id,
                    sample_id:this.infoFormList.sample_id,
                    type:this.infoFormList.type,
                    send_time:send_time,
                    phone_list:phone_list,
                    key:this.infoFormList.type == 2?this.infoFormList.key:""
                }
                // console.log(data);
                sendMessage(data).then((res)=>{
                    if(res.code==0){
                        this.tab_view = 1;
                        this.beforeUpload();
                        this.clearDate();
                        this.listArray();
                    }
                }).catch((res)=>{
                    if(res.code==0){
                        this.$message.success({message:res.message,duration:5000});
                        this.tab_view = 1;
                        this.beforeUpload();
                        this.clearDate();
                        this.listArray();
                    }
                })
            },
            saveTime(){
                let myDate = new Date();
                let Month = myDate.getMonth() +1;       // 获取当前月份(0-11,0代表1月)
                let date = myDate.getDate();        // 获取当前日(1-31)
                let Hours = myDate.getHours();       // 获取当前小时数(0-23)

                let time = this.infoFormList.sendTime.split(" ");  // 选择的时间
                let timeYea = time[0].split("-")[0];
                let timeMon = time[0].split("-")[1];
                let timeDa = time[0].split("-")[2];
                let timeHou = time[1].split(":")[0];

                if(Month == timeMon && date == timeDa && Hours >= timeHou ){
                    this.$message.error("请重新选择发送时间");
                    return false
                }else{
                    return true
                }
            },
            dialongFetchData(){  //弹框里的搜索
                this.formDialongList = [];
                this.formDialongInline.listLoading = true;
                this.formDialong.begin_time = this.formDialongPickerDate[0];
                this.formDialong.end_time = this.formDialongPickerDate[1];
                getMessageInfoPage(this.formDialong).then(response=>{
                    this.formDialongInline.totalDataNumber = response.data.count / 1;
                    if (this.formDialongInline.totalDataNumber == 0) {
                        this.formDialongInline.listLoading = false;
                    } else {
                        getMessageInfo(this.formDialong).then(res=>{
                            this.formDialongList = res.data;
                            this.formDialongInline.listLoading = false;
                        });
                    }
                });
            },
            dialongCurrentChange(val){
                this.formDialongInline.listLoading = true;
                getMessageInfo(this.formDialong,val).then(res=>{
                    this.formDialongList = res.data;
                    this.formDialongInline.listLoading = false;
                }).catch(res => {
                    this.formDialongInline.listLoading = false;
                });
            },
            backClick() {  //详情里的返回按钮
                if (!this.isDisabled) {
                    this.$confirm(
                        "返回后已修改的数据不会保存，是否放弃本次操作？",
                        "提示",
                        {type: "warning"}
                    ).then(() => {
                        this.tab_view = 1;
                        this.beforeUpload();
                        this.clearDate();
                    });
                }else{
                    this.tab_view = 1;
                    this.beforeUpload();
                    this.clearDate();
                }
            },
            clearDate(){
              this.infoFormList={
                  sample_id:"",
                  name:"",
                  content:"",
                  type:"",
                  phone:"",
                  key:"",
                  sendType:"",
                  sendTime:""
                }
            },
            goStep(i) { //详情
                if (this.isNew == 1) {
                    return;
                }
                if (this.isDisabled) {
                    this.tab_step = i;
                }
            },
            goNext(){
                if (!this.verify()) {
                    return;
                }
                this.tab_step++;
            },
            verify() {
                if (this.tab_view == 1) {
                    return;
                }
                let isPass = false;
                if (this.tab_step == 1) {
                    isPass = true;
                } else if (this.tab_step == 2) {
                    if(this.infoFormList.type){
                        if(this.infoFormList.type==2){
                            if(this.phone_num<=0){
                                this.$message.error("请导入有效的手机号");
                            }else {
                                isPass = true;
                            }
                        }else {
                            if(!mobile(this.infoFormList.phone)){
                                this.$message.error("请输入正确的手机号");
                            }else{
                                isPass = true;
                            }
                        }
                    }else{
                        this.$message.error("请选择发送对象");
                        isPass = false;
                    }
                } else if (this.tab_step == 3) {
                    if (this.selectlist.length==0) {
                        this.$message.error("请选择选择商品/券");
                        isPass = false;
                    } else {
                        isPass = true;
                    }
                }
                return isPass;
            },
            beforeUpload() {
                this.$refs.upload.clearFiles();
                this.user_phone = [];
                this.user_bad_phone = [];
                this.phone_num_list = [];
                this.phone_num = -1;
                this.bad_phone_num = 0;
                this.infoFormList.key = "";
            },
            uploadChange(file) {
                this.beforeUploadLoading = true;
                this.getFile(file.raw)
                    .then((res) => {
                        this.user_phone = res.code == 1 ? res.batteryArr : [];
                        let phone_list = [];
                        this.user_phone.sort().forEach((val, i) => {
                            if (mobile(val) && val != this.user_phone[i + 1]) {
                                phone_list.push(val);
                            } else {
                                this.user_bad_phone.push(val);
                            }
                        });
                        if (phone_list.length > 0 && phone_list.length <= 50000) {
                            return importPhone({ phone_list });
                        } else if (phone_list.length > 50000) {
                            return { code: -2 };
                        } else {
                            return { code: -1 };
                        }
                    })
                    .then((res) => {
                        if (res.code == 1) {
                            this.user_bad_phone.unshift(...res.data.invalid);
                            this.bad_phone_num = this.user_bad_phone.length;
                            this.phone_num = res.data.valid.length;
                            res.data.valid.forEach(val=>{
                                this.phone_num_list.push(val.mobile)
                            });
                            this.infoFormList.key = res.data.key;
                        } else if (res.code == -1) {
                            this.bad_phone_num = this.user_bad_phone.length;
                            this.phone_num = 0;
                        } else if (res.code == -2) {
                            this.$message.error("导入数量超过50000条，请重新操作");
                        }
                        this.beforeUploadLoading = false;
                    });
            },
            getFile(file) {
                let _this = this;
                return new Promise(function (resolve, reject) {
                    // 返回Promise对象
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        // 异步执行
                        try {
                            // 以二进制流方式读取得到整份excel表格对象
                            let data = e.target.result,
                                workbook = XLSX.read(data, { type: "binary" });
                            let batteryArr = [];
                            let str = "^" + ["!ref", "!margins", "A1"].join("|") + "$";
                            let reg = new RegExp(str);
                            for (let item in workbook.SheetNames) {
                                let SheetName = workbook.SheetNames[item];
                                let sheetInfos = workbook.Sheets[SheetName];
                                for (let battery in sheetInfos) {
                                    if (!reg.test(battery) && sheetInfos[battery].v) {
                                        batteryArr.push(sheetInfos[battery].v);
                                    }
                                }
                            }
                            resolve({ code: 1, batteryArr });
                        } catch (e) {
                            reject(e.message);
                        }
                    };
                    reader.readAsBinaryString(file);
                });
            },
            //下载模板
            uploadTemplate() {
                let sheet = [["用户手机号"]];
                this.uploadExcel(sheet, "用户手机号");
            },
            //导出无效手机号
            uploadPhone() {
                this.uploadBadLoading = true;
                setTimeout(() => {
                    let sheet = [["无效手机号"]];
                    this.user_bad_phone.forEach((val) => {
                        sheet.push([val]);
                    });
                    this.uploadExcel(sheet, "无效手机号");
                    this.uploadBadLoading = false;
                }, 0);
            },
            //excel导出
            uploadExcel(sheet, wb_name, wch = 14) {
                //列宽
                let wscols = [{ wch }];
                //生成工作表
                let ws = XLSX.utils.aoa_to_sheet(sheet);
                //生成工作簿
                let wb = XLSX.utils.book_new();
                //设置列宽
                ws["!cols"] = wscols;
                //将工作表添加至工作簿中
                XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
                XLSX.writeFile(wb, `${wb_name}.xlsx`);
            },
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .info {
        background: #fff;
        padding: 30px 0 10px;
        margin-bottom: 20px;
    }

    .tab_title {
        width: 200px;
        font-size: 20px;
        font-weight: bold;
        margin: 5px 0 20px 70px;
    }

    .op_title {
        margin: 30px 0 20px;
        font-size: 16px;
        font-weight: bold;
        color: #282828;
        padding:0 0 10px 20px;
        box-sizing: border-box;
        border-bottom: 1px solid #dcdfe6;
    }
    .upload {
        display: flex;
        margin-top: 20px;
        position: relative;
        .download {
            position: absolute;
            top: 0;
            left: 120px;
            // margin-left: 20px;
        }
    }
    .upload_info {
        font-size: 14px;
        .upload_info_title {
            font-weight: bold;
        }
        .upload_info_num {
            margin-top: 15px;
        }
        .upload_info_bad_num {
            color: #f56c6c;
        }
        .upload_remark {
            margin-top: 15px;
            color: #999;
        }
    }
</style>